package com.ruoyi.quartz.task;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.ruoyi.common.core.domain.entity.SysUser;
import com.ruoyi.common.exception.job.TaskException;
import com.ruoyi.common.utils.http.HttpUtils;
import com.ruoyi.form.domain.FormLog;
import com.ruoyi.form.domain.FormRegister;
import com.ruoyi.form.dto.FormRegisterSqDto;
import com.ruoyi.form.dto.FormRegisterZkDto;
import com.ruoyi.form.service.IFormLogService;
import com.ruoyi.form.service.IFormRegisterService;
import com.ruoyi.quartz.domain.SysJob;
import com.ruoyi.quartz.service.ISysJobService;
import com.ruoyi.system.domain.SysConfig;
import com.ruoyi.system.service.ISysConfigService;
import com.ruoyi.system.service.ISysUserService;
import org.apache.commons.beanutils.BeanUtils;
import org.apache.commons.collections4.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.quartz.SchedulerException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.Date;
import java.util.List;
import java.util.Random;

@Component("excelTask")
public class ExcelTask {

    private static final Logger log = LoggerFactory.getLogger(ExcelTask.class);
    @Autowired
    private IFormRegisterService formRegisterService;
    @Autowired
    private ISysUserService userService;
    @Autowired
    private IFormLogService logService;
    @Autowired
    private ISysJobService jobService;
    @Autowired
    private ISysConfigService configService;

    public void execlTask() {
        log.info("开始执行表格定时任务>>>>>>>>>>>>>>>>>>>>");
        try {
            SysConfig sysConfig = configService.selectConfigById(12L);
            SysConfig sysConfig1 = configService.selectConfigById(13L);
            String zkUrl = sysConfig.getConfigValue();
            String sqUrl = sysConfig1.getConfigValue();
            FormRegister formRegister = new FormRegister();
            formRegister.setState(1);
            List<FormRegister> list = formRegisterService.selectFormRegisterList2(formRegister);
            if(CollectionUtils.isNotEmpty(list)){
                for (FormRegister register : list) {
                    if(register.getUserId() != null){
                        SysUser sysUser = userService.selectUserById(register.getUserId());
                        Integer sendCount = sysUser.getSendCount();
                        if(sendCount != null && sendCount > 0){
                            FormRegisterZkDto zkDto = new FormRegisterZkDto();
                            BeanUtils.copyProperties(zkDto,register);
                            String zkStr = JSON.toJSONString(zkDto);
                            String zkBody = HttpUtils.postBody(zkUrl, zkStr); //撞库接口返回
                            log.info("撞库接口数据返回：{}，ID：{}",zkBody,register.getId());
                            if(StringUtils.isNotBlank(zkBody)){
                                JSONObject jsonObject = JSON.parseObject(zkBody);
                                Integer code = jsonObject.getInteger("code");
                                if(code == 0){  //除了0都是失败
                                    //插入日志
                                    FormLog formLog = new FormLog();
                                    formLog.setState(1);
                                    formLog.setApiType(1);
                                    formLog.setParamDesc(zkStr);
                                    formLog.setRegisterId(register.getId());
                                    formLog.setCreateTime(new Date());
                                    formLog.setApiDesc(zkBody);
                                    logService.insertFormLog(formLog);


                                    //调用申请接口
                                    FormRegisterSqDto sqDto = new FormRegisterSqDto();
                                    BeanUtils.copyProperties(sqDto,register);
                                    String sqStr = JSON.toJSONString(sqDto);
                                    String sqBody = HttpUtils.postBody(sqUrl, sqStr);
                                    log.info("申请接口数据返回：{}，ID：{}",sqBody,register.getId());
                                    if(StringUtils.isNotBlank(sqBody)){
                                        JSONObject sqObject = JSON.parseObject(sqBody);
                                        Integer sqCode = sqObject.getInteger("code");
                                        if(sqCode == 0){
                                            FormLog formLog1 = new FormLog();
                                            formLog1.setState(1);
                                            formLog1.setApiType(2);
                                            formLog1.setParamDesc(sqStr);
                                            formLog1.setRegisterId(register.getId());
                                            formLog1.setCreateTime(new Date());
                                            formLog1.setApiDesc(sqBody);
                                            logService.insertFormLog(formLog1);

                                            //扣user数量
                                            userService.updateCount(sysUser.getUserId(),sendCount-1);

                                            //修改状态
                                            register.setState(2);
                                            register.setFlag(1);
                                            int i = formRegisterService.updateFormRegister(register);
                                        }else {
                                            FormLog formLog1 = new FormLog();
                                            formLog1.setState(2);
                                            formLog1.setApiType(2);
                                            formLog1.setParamDesc(sqStr);
                                            formLog1.setRegisterId(register.getId());
                                            formLog1.setCreateTime(new Date());
                                            formLog1.setApiDesc(sqBody);
                                            logService.insertFormLog(formLog1);

                                            register.setState(2);
                                            register.setFlag(2);
                                            int i = formRegisterService.updateFormRegister(register);
                                        }
                                    }
                                }else {
                                    FormLog formLog = new FormLog();
                                    formLog.setState(2);
                                    formLog.setApiType(1);
                                    formLog.setParamDesc(zkStr);
                                    formLog.setRegisterId(register.getId());
                                    formLog.setCreateTime(new Date());
                                    formLog.setApiDesc(zkBody);
                                    logService.insertFormLog(formLog);

                                    register.setState(2);
                                    register.setFlag(2);
                                    int i = formRegisterService.updateFormRegister(register);
                                }

                            }
                        }
                    }
                }
            }
        }catch (Exception e){
            updateTaskConfig();
            log.error("表格定时任务执行异常>>>>>>>>>>：{}",e.getMessage());
        }
        updateTaskConfig();
        log.info("执行表格定时任务结束>>>>>>>>>>>>>>>>>>>>");
    }

    private void updateTaskConfig(){
        SysJob sysJob = jobService.selectJobById(100L);
        String cronExpression = sysJob.getCronExpression();
        Random random = new Random();
        int randomNumber = random.nextInt(5) + 1;
        String s = cronExpression.substring(0, 4) + randomNumber + cronExpression.substring(5);
        sysJob.setCronExpression(s);
        try {
            jobService.updateJob(sysJob);
        } catch (SchedulerException e) {
            log.error("修改任务异常");
            throw new RuntimeException(e);
        } catch (TaskException e) {
            log.error("修改任务异常");
            throw new RuntimeException(e);
        }
    }

}
